package com.viewpagertext.adapters;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.sshtools.j2ssh.util.Hash;
import com.viewpagertext.R;
import com.viewpagertext.constructor.Song;

import java.io.File;
import java.security.acl.Group;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;

/**
 * @author ironjam
 * @version 1.0
 * @project AndroidMusic-master
 * @description
 * @date 2024/6/10 11:56:55
 */

public class LocalGroupRecAdapter extends RecyclerView.Adapter<LocalGroupRecAdapter.NewViewHolder> {
    private Context context;
    private ArrayList<String> groupName;
    private HashMap<String, List<Song>> itemMap;
    private String flag;
    private List<Song> list;
    private OnItemClickListener mListener;


    public LocalGroupRecAdapter(Context context, List<Song> list, String flag) {
        this.context = context;
        this.flag = flag;
        this.list = list;// 歌曲列表
        groupName = new ArrayList<>();
        itemMap = new HashMap<>();
        initlist(flag);
    }

    private void initlist(String flag) {
        switch (flag) {
            case "album":
                sortByAlbum();
                break;
            case "singer":
                sortBySinger();
                break;
            case "fold":
                sortByFold();
                break;
        }
        Collections.sort(groupName, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return toPinyinString(s1).toLowerCase().compareTo(toPinyinString(s2).toLowerCase());
            }
        });
    }

    private String toPinyinString(String string) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            if (isChineseCharacter(c)) {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
                if (pinyinArray != null && pinyinArray.length > 0) {
                    sb.append(pinyinArray[0]); // 使用第一个拼音
                } else {
                    sb.append(c); // 如果不是汉字，直接添加到结果中
                }
            } else {
                sb.append(c); // 如果不是汉字，直接添加到结果中
            }
        }
        return sb.toString();
    }

    private boolean isChineseCharacter(char c) {
        Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
        return (block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT);
    }

    @NonNull
    @Override
    public NewViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        NewViewHolder newViewHolder = new NewViewHolder(LayoutInflater.from(context).inflate(R.layout.local_group_layout, parent, false));
        return newViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull NewViewHolder newViewHolder, int i) {
        Collections.sort(groupName, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return toPinyinString(s1).compareTo(toPinyinString(s2));
            }
        });
        newViewHolder.t_position.setText(i + 1 + "");
        newViewHolder.t_group_name.setText(groupName.get(i));
        newViewHolder.t_count.setText(itemMap.get(groupName.get(i)).size() + "首");
        newViewHolder.localmenu.setImageBitmap(BitmapFactory.decodeFile(itemMap.get(groupName.get(i)).get(0).picPath));
        if (flag.equals("fold")) {
            newViewHolder.localmenu.setImageResource(R.mipmap.fold);
        }
        newViewHolder.t_position.setTag(i);
        newViewHolder.t_group_name.setTag(i);
        newViewHolder.t_count.setTag(i);
        newViewHolder.localmenu.setTag(i);

        final String name = groupName.get(i);
        final List<Song> songs = itemMap.get(name);
        newViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mListener != null) {
                    mListener.onItemClick(name, songs);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return groupName.size();
    }

    private void sortByAlbum() {
        groupName.clear();
        itemMap.clear();
        for (Song song : list) {
            String album = song.album;
            if (!groupName.contains(album)) {
                groupName.add(album);
            }
            List<Song> songList = itemMap.get(album);
            if (songList == null) {
                songList = new ArrayList<>();
            }
            songList.add(song);
            itemMap.put(album, songList);
        }
    }

    private void sortBySinger() {
        groupName.clear();
        itemMap.clear();
        for (Song song : list) {
            String allsingers = song.singer;
            String[] singers = allsingers.split("&");
            for (String singer : singers) {
                if (!groupName.contains(singer)) {
                    groupName.add(singer);
                }
                List<Song> songList = itemMap.get(singer);
                if (songList == null) {
                    songList = new ArrayList<>();
                }
                songList.add(song);
                itemMap.put(singer, songList);
            }
        }
    }

    private void sortByFold() {
        groupName.clear();
        itemMap.clear();
        for (Song song : list) {
            String filePath = song.path;
            String dirName = new File(filePath).getParentFile().getName();
            if (!groupName.contains(dirName)) {
                groupName.add(dirName);
            }
            List<Song> songList = itemMap.get(dirName);
            if (songList == null) {
                songList = new ArrayList<>();
            }
            songList.add(song);
            itemMap.put(dirName, songList);
        }
    }

    public void notifyDataSetChanged(List<Song> list) {
        this.list = list;
        initlist(flag);
        super.notifyDataSetChanged();
    }

    class NewViewHolder extends RecyclerView.ViewHolder {

        private TextView t_position, t_group_name, t_count;
        private ImageView localmenu, more_image_view;

        public NewViewHolder(@NonNull View itemView) {
            super(itemView);
            t_position = itemView.findViewById(R.id.t_postion);
            t_group_name = itemView.findViewById(R.id.t_group_name);
            t_count = itemView.findViewById(R.id.t_count);
            localmenu = itemView.findViewById(R.id.localmenu);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(String groupName, List<Song> songs);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

}
